import 'dart:convert';
import 'dart:ui';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:magic_car/jiance/car_info.dart';
import 'package:magic_car/jiance/car_shouxu.dart';
import 'package:magic_car/jiance/inspectresult.dart';
import 'package:magic_car/jiance/jianceorder.dart';
import 'package:magic_car/jiance/papularinspect.dart';
import 'package:magic_car/jiance/qimian.dart';
import 'package:magic_car/jiance/qinpao.dart';

import 'package:magic_car/jiance/uppics.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class StartJianPage extends StatefulWidget {
  final String oid;
  final String titles;
  final String orderStatus;
  final int type;

  StartJianPage(this.oid, this.titles, this.orderStatus, this.type);
  @override
  _MyHomePageState createState() =>
      new _MyHomePageState(this.oid, this.titles, this.orderStatus, this.type);
}

class _MyHomePageState extends State<StartJianPage> {
  final String oid;
  final String titles;
  final String orderStatus;
  final int type;
  _MyHomePageState(this.oid, this.titles, this.orderStatus, this.type);
  List formList;
  List testItem;
  bool loaddata = false;
  String status;
  Map formalities;
  Map oldformalities;
  FlutterBlue flutterBlue = FlutterBlue.instance;
  BluetoothDevice device;
  bool showUrl = false;
  @override
  deactivate() async {
    var bool = ModalRoute.of(context).isCurrent;

    if (bool) {
      //页面有返回时
      if (orderStatus == "0") {
        SharedPreferences pref = await SharedPreferences.getInstance();
        if (pref.getBool('shouxusave') != null) {
          var issave = pref.getBool('shouxusave');
          if (issave) {
            // subOrder();
          }
        }
      }
    }
  }

  initState() {
    super.initState();
    formList = [
      {
        "title": '客户姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
    //loadTestItem();
    formalities = {
      "invoice": '', //购车发票/过户票
      "Tax": '', //购置税证
      "vehicle": '', //行驶证
      "vehicles_b_time": '', //年检有效期开始时间
      "yearcheck_e_time": '', //年检有效期结束时间
      "registration": '', //登记证
      "transfer": '', //过户次数
      "compu_b_time": '', //交强险有效期 begin
      "compu_e_time": '', //交强险有效期 end
      "compu_name": '', //交强险保险公司
      "vehicles_b_time": '', //车船税有效期 start
      "vehicles_e_time": '', //车船税有效期 end
      "business_b_time": '', // 商业保险有效期 start
      "business_e_time": '', //商业保险有效期  end
      "business_sell_by_car": false, //商业险随车出售
      "business_price": '', //商业险金额
      "business_name": '', //商业保险公司
      "nameplate": '', //车身铭牌
      "busines": '', //是否有商业险
      "compu": '', //是否有交强险
      "vehicles": '', //车船税是否
      "compu_name1": '',
      "business_name": ''
    };
    loaddetail();
    // connect();
  }

  connect() async {
    flutterBlue.scan().listen((scanresult) {
      device = scanresult.device;
      String deveceName = device.name;
      if (deveceName.startsWith('LS')) {
        startconnetc();
      }
    });
    flutterBlue.stopScan();
  }

  startconnetc() async {
    await device.connect();
    List<BluetoothService> services = await device.discoverServices();
    services.forEach((service) async {
      // do something with service
      var characteristics = service.characteristics;
      for (BluetoothCharacteristic c in characteristics) {
        // List<int> value = await c.read();
        // print(value);
        await c.setNotifyValue(true);
        c.value.listen((value) {
          print('值发生改变');
          print(value is List);
          print(value);
          //print(value.length);
          if (value.length > 0) {
            //第一位先转换为16进制
            print(value[8].toRadixString(16).toUpperCase());
            var hexStr = "";
            if (value[9] == 255) {
              //负数
            } else {
              if (value[8] < 10) {
                hexStr = '0' +
                    value[11].toString() +
                    '0' +
                    value[10].toString() +
                    '0' +
                    value[9].toString() +
                    '0' +
                    value[8].toString();
              } else {
                hexStr = '0' +
                    value[11].toString() +
                    '0' +
                    value[10].toString() +
                    '0' +
                    value[9].toString() +
                    value[8].toRadixString(16).toUpperCase();
              }
              print(hexStr);
              print('转换结果' + _hexToInt(hexStr).toString());
            }
//  // print(_hexToInt('0000015d'));
//   var h = 59506490075;
// //进制转换方法
//   print("整型转换为16进制: $h -> 0x${h.toRadixString(16).toUpperCase()}");
          }
          // do something with new value
        });
      }
    });
  }

//16进制转换成10进制数值
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;

    if (loaddata == false) {
      content = new Column(
          children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
          //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
          );
      return content;
    }
    List topinfoarr = [
      {
        "title": '相关信息：',
        'title_color': Color.fromRGBO(31, 31, 31, 1),
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'ishead': "1"
      },
      {
        "title": '订单信息',
        'title_color': Color.fromRGBO(51, 51, 51, 1),
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'ishead': "0"
      },
      {
        "title": '手续信息',
        'title_color': Color.fromRGBO(51, 51, 51, 1),
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'ishead': "0"
      },
      // {
      //   "title": '车辆信息',
      //   'title_color': Color.fromRGBO(51, 51, 51, 1),
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'ishead': "0"
      // },
    ];
    if (type == 2) topinfoarr.removeAt(1);
    for (var i = 0; i < topinfoarr.length; i++) {
      var item = topinfoarr[i];
      double padtop = i == 1 ? 0 : 1;
      Color colors =
          i == 0 ? item["title_color"] : Color.fromRGBO(102, 102, 102, 1);
      Widget topinfo = Padding(
          padding: new EdgeInsets.fromLTRB(0, padtop, 0, 0),
          child: Container(
              color: Colors.white,
              height: 50,
              child: new GestureDetector(
                  onTap: () {
                    if (i == 0) return;

                    if (i == 1) {
                      //订单信息
                      if (type == 1) {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return new JIanceOrderPage(this.oid);
                        }));
                      } else {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return new CarshouxuPage(
                              this.oid, formalities, this.type);
                        }));
                      }
                    } else if (i == 2) {
                      //手续信息
                      // Navigator.of(content).push
                      print(formalities);
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new CarshouxuPage(
                            this.oid, formalities, this.type);
                      }));
                    } else if (i == 3) {
                      //车辆信息
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new CarinfoPage(this.oid);
                      }));
                    }
                  },
                  child: new Row(
                    children: <Widget>[
                      Expanded(
                        child: new Padding(
                            padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                            child: new Text(
                              item["title"],
                              style: TextStyle(fontSize: 15, color: colors),
                            )),
                        flex: 1,
                      ),
                      new Padding(
                          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                          child: i != 0
                              ? new Image.asset(
                                  'resource/images/user/detail.png',
                                  height: 20,
                                )
                              : new Text('')),
                    ],
                  ))));

      tiles.add(topinfo);
    }
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new Row(
              children: <Widget>[
                Expanded(
                  child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: new Text(
                        "其他信息",
                        style: TextStyle(
                            fontSize: 15, color: Color.fromRGBO(31, 31, 31, 1)),
                      )),
                  flex: 1,
                ),
              ],
            ))));

    for (int i = 0; i < testItem.length; i++) {
      var item = testItem[i];
      double toppad = 1;
      if (i == 0) toppad = 0;
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, toppad, 0, 0),
          child: Container(
              color: Colors.white,
              height: 50,
              child: new GestureDetector(
                  onTap: () {
                    if (status == "2" || status == "3") {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new PapularinspectReult(item);
                      }));
                    } else {
                      if (item["id"] == "4000") {
                        //照片上传单独检测页面
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return new Uppic(item);
                        }));
                      } else if (item["id"] == "3040") {
                        //漆面检测单独页面
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return new Qimianinspect(item);
                        }));
                      } else if (item["id"] == "3044") {
                        //浸泡检测单独
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return new Qinpaoinspect(item);
                        }));
                      } else {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return new Papularinspect(item);
                        }));
                      }
                    }
                  },
                  child: new Row(
                    children: <Widget>[
                      Expanded(
                        child: new Padding(
                            padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                            child: new Text(
                              item['name'],
                              style: TextStyle(
                                  fontSize: 15,
                                  color: Color.fromRGBO(102, 102, 102, 1)),
                            )),
                        flex: 1,
                      ),
                      new Padding(
                          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                          child: new Image.asset(
                            'resource/images/user/detail.png',
                            height: 20,
                          )),
                    ],
                  )))));
    }
    if (orderStatus == "0" || orderStatus == "1") {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 30),
          child: new Container(
              color: Color.fromRGBO(239, 239, 239, 1),
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: new Material(
                    color: Color.fromRGBO(239, 239, 239, 1),
                    //INK可以实现装饰容器
                    child: new Ink(
                      //用ink圆角矩形
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      decoration: new BoxDecoration(
                        //背景

                        color: Color.fromRGBO(27, 182, 251, 1),
                        //设置四周圆角 角度
                        borderRadius: BorderRadius.all(Radius.circular(18.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Color.fromRGBO(27, 182, 251, 1)),
                      ),
                      child: new InkWell(

                          //圆角设置,给水波纹也设置同样的圆角
                          //如果这里不设置就会出现矩形的水波纹效果
                          borderRadius: new BorderRadius.circular(15.0),
                          //设置点击事件回调
                          onTap: () {
                            // submit();
                            subOrder(0);
                          },
                          child: Container(
                            //设置 child 居中
                            alignment: Alignment(0, 0),
                            height: 36,
                            //color: Color.fromRGBO(239, 239, 239, 1),
                            width: double.infinity,
                            child: Text(
                              "检测完成，提交",
                              style: TextStyle(color: Colors.white),
                            ),
                          )),
                    ),
                  )))));
    }
    if (type == 2 && orderStatus == "3") {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 30),
          child: new Container(
              color: Color.fromRGBO(239, 239, 239, 1),
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: new Material(
                    color: Color.fromRGBO(239, 239, 239, 1),
                    //INK可以实现装饰容器
                    child: new Ink(
                      //用ink圆角矩形
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      decoration: new BoxDecoration(
                        //背景

                        color: Color.fromRGBO(27, 182, 251, 1),
                        //设置四周圆角 角度
                        borderRadius: BorderRadius.all(Radius.circular(18.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Color.fromRGBO(27, 182, 251, 1)),
                      ),
                      child: new InkWell(

                          //圆角设置,给水波纹也设置同样的圆角
                          //如果这里不设置就会出现矩形的水波纹效果
                          borderRadius: new BorderRadius.circular(15.0),
                          //设置点击事件回调
                          onTap: () {
                            // submit();
                            subOrder(1);
                          },
                          child: Container(
                            //设置 child 居中
                            alignment: Alignment(0, 0),
                            height: 36,
                            //color: Color.fromRGBO(239, 239, 239, 1),
                            width: double.infinity,
                            child: Text(
                              "生成检测报告",
                              style: TextStyle(color: Colors.white),
                            ),
                          )),
                    ),
                  )))));
    }
    if (showUrl) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
          child: new Container(
              color: Color.fromRGBO(239, 239, 239, 1),
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: Align(
                      alignment: Alignment.center,
                      child: new Text('报告已生成，点击下方链接，在电脑端查看和打印'))))));
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
          child: new Container(
              color: Color.fromRGBO(239, 239, 239, 1),
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: Align(
                      alignment: Alignment.center,
                      child: FlatButton(
                          onPressed: () {
                            Clipboard.setData(ClipboardData(
                                text:
                                    'http://ylz.9ok6.com/app/index.php?i=16&c=entry&m=chemogu&do=mobile&r=car.test_reports&id=' +
                                        this.oid +
                                        '&type=2'));
                            Toast.show('链接已复制', context);
                          },
                          child: new Text(
                              'http://ylz.9ok6.com/app/index.php?i=16&c=entry&m=chemogu&do=mobile&r=car.test_reports&id=' +
                                  this.oid +
                                  '&type=2')))))));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  loaddetail() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    String api = HttpHelper.API_OrderDetail;
    if (this.type == 2) {
      api = HttpHelper.API_BussinessOrderDetail;
    }
    HttpHelper.post(api, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          if (data["info"]["status"] != "0" && data["info"]["status"] != "1") {
            setState(() {
              testItem = data["info"]["inspectorItemsResult"]["otherData"]
                  ["checkData"];
                  oldformalities = data["info"]["inspectorItemsResult"]["formalities"];
              loaddata = true;
              status = data["info"]["status"].toString();
            });
            // if (data["info"]["inspectorItemsResult"] != null) {
            // if (type == 1) {
            //   setState(() {
            //     testItem = data["info"]["inspectorItemsResult"]["otherData"]
            //         ["checkData"];
            //     loaddata = true;
            //     status = data["info"]["status"].toString();
            //   });
            // }else{
            //   setState(() {

            //     loaddata = true;
            //     status = data["info"]["status"].toString();
            //   });
            // }
          } else {
            print('获取系统检测项');
            loadTestItem(data["info"]["test_type"]);
          }
          // List oldlist = formList;
          // var orderinfo = data["info"];
          // for(var i =0;i<oldlist.length;i++){
          //   var item = oldlist[i];
          //   var str = "";
          //   if(i==0) str = orderinfo["name"];
          //   else if(i==1) str = orderinfo["phone_num"];
          //   else if(i==2) str = orderinfo["name"];
          //   else if(i==3) str = orderinfo["phone_num"];
          //   else if(i==4) str = orderinfo["add_time"];
          //   else str = orderinfo["address"];

          //   item["sub_title"]=str;
          // }

          setState(() {
            //formList = oldlist;
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  //加载检测项
  loadTestItem(type) {
    print('加载检测项');
    var types = 1;
    if (type == "事故检测")
      types = 2;
    else if (type == "保修检测") types = 3;
    Map<String, String> map = new Map();
    map["type"] = types.toString();
    HttpHelper.post(HttpHelper.API_LoadTestItem, (data) async {
      if (data != null) {
        setState(() {
          testItem = data;
          loaddata = true;
        });
      }
    }, params: map);
  }

  //提交检测项
  subOrder(types) {
    print('订单状态');
    print(this.status);
    // if (this.orderStatus == "0"||this.orderStatus == "1") {
    Map<String, Object> map = new Map();
    map["oid"] = this.oid;
    map["type"] = this.type.toString();
    if (types == 1) {
      for (var item in testItem) {
        for (var items in item["post"]) {
          if (items["show_report"] == "是") {
            items["show_report"] = "1";
          }
          if (items["show_report"] == "否") {
            items["show_report"] = "0";
          }
        }
      }
    }
    Map chechdata1 = {"checkData": testItem};
    
    Map checkdata = {"otherData": chechdata1, "formalities": formalities};
    if(types==1){
      //生成报告单时，手续信息不变
      checkdata = {"otherData": chechdata1,"formalities":oldformalities};
    }
    // checkdata["otherData"]["checkData"]=testItem;
    // map["inspector"] = jsonEncode(testItem);
    map["inspector"] = jsonEncode(checkdata);
    // print('传递的检测项');
    print(map);
    HttpHelper.post(HttpHelper.API_SubOrder, (data) async {
      if (data != null) {
        Toast.show(data["msg"], context);
        // print('上传检测项');
        // print(data);
        if (data["code"].toString() == "1") {
          if (types == 1) {
            setState(() {
              showUrl = true;
            });
          } else {
            Navigator.pop(context);
          }
        }
      }
    }, params: map);
    // }
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(this.titles),
        backgroundColor: Colors.white,
        // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        elevation: 0,
      ),
      body: new Center(
          child: Container(
        decoration: new BoxDecoration(
          color: Color.fromRGBO(238, 238, 238, 1),
        ),
        child: Padding(
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
            child: new ListView(
              children: <Widget>[buildcontent()],
            )),
      )),
    );
    // if (orderStatus == "0") {
    //   return WillPopScope(
    //     child: new Scaffold(
    //         appBar: new AppBar(
    //           title: new Text(this.titles),
    //           backgroundColor: Colors.white,
    //           iconTheme: new IconThemeData(color: Colors.black),
    //           elevation: 0,
    //           // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
    //         ),
    //         body: new Center(
    //             child: Container(
    //           decoration: new BoxDecoration(
    //             color: Color.fromRGBO(238, 238, 238, 1),
    //           ),
    //           child: Padding(
    //               padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
    //               child: new ListView(
    //                 children: <Widget>[buildcontent()],
    //               )),
    //         ))),
    //     onWillPop: () => willpop(),
    //   );
    // } else {
    //   return new Scaffold(
    //     appBar: new AppBar(
    //       title: new Text(this.titles),
    //       backgroundColor: Colors.white,
    //       // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
    //       elevation: 0,
    //     ),
    //     body: new Center(
    //         child: Container(
    //       decoration: new BoxDecoration(
    //         color: Color.fromRGBO(238, 238, 238, 1),
    //       ),
    //       child: Padding(
    //           padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
    //           child: new ListView(
    //             children: <Widget>[buildcontent()],
    //           )),
    //     )),
    //   );
    // }
  }

  Future<bool> willpop() {
    _showDialog();
    return Future.value(false);
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('是否已检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    subOrder(0);
                    Navigator.of(this.context).pop();
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}
